package com.litbw.gui;

import java.awt.BorderLayout;

import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.litbw.event.Event;
import com.litbw.publicobservable.BasicUIMessage;
import com.litbw.publicobservable.EventDetailMessage;

/**
 * The EventPanel uses a JList panel with custom renderer to display the
 * events from the Event Table in the database.
 * @author Michael Morris
 *
 */
public class EventPanel extends AbstractObservablePanel {

	/**
	 * Generated serial version UID.
	 */
	private static final long serialVersionUID = -7279227028589593674L;
	
	/**
	 * The default name to use for this panel.
	 */
	private static final String DEF_NAME = "Upcoming Events";
		
	/**
	 * Create a new instance of the Event panel.
	 */
	public EventPanel() {
		
		super();

		setLayout(new BorderLayout());
		setName(DEF_NAME);
		
		addComponents();
		
	}
	
	/**
	 * Add the sub components of the EventPanel
	 */
	private void addComponents() {
		
		// Simply add a list
		final EventList list = new EventList();
		list.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				
				// Use the adjusting flag to make sure we don't get multiple
				// events firing on the same change of selectino.
				if (!e.getValueIsAdjusting()) {
					showEventDetail(list.getEventAt(list.getSelectedIndex()));
				}
			}
			
		});
		
		final JScrollPane scroll = new JScrollPane(list);
		scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		
		add(scroll, BorderLayout.CENTER);
		
	}
	
	/**
	 * Signal to the EventDetailPanel to update with the given user. Next
	 * signal UI to show the EventDetailPanel.
	 * @param e The event to display in the event detail page.
	 */
	private void showEventDetail(final Event e) {
		
		if (e != null) {
			// Signal to the event detail page to update it's contents with
			// the given event.
			setChanged();
			notifyObservers(new EventDetailMessage(EventDetailMessage.EventDetailSignal.UPDATE, e));
			
			// Signal to the UI to show the events detail page.
			setChanged();
			notifyObservers(new BasicUIMessage(BasicUIMessage.UISignal.SHOW_EVENT_DETAIL));
		}
		
	}
	
}
